<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
          <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
<!--        <el-date-picker-->
<!--          v-model="query.createTime"-->
<!--          :default-time="['00:00:00','23:59:59']"-->
<!--          type="daterange"-->
<!--          range-separator=":"-->
<!--          size="small"-->
<!--          class="date-item"-->
<!--          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--          start-placeholder="createTimeStart"-->
<!--          end-placeholder="createTimeEnd"-->
<!--        />-->
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="900px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="130px">
          <el-form-item label="中文标题">
            <el-input v-model="form.title" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="中文简介">
            <el-input v-model="form.intro" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="中文内容">
            <editor-bar v-model="form.content" :key="form.id" :is-clear="isClear" @change="change" />
          </el-form-item>
          <el-form-item label="作者">
            <el-input v-model="form.author" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="form.createTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="英文标题">
            <el-input v-model="form.englishTitle" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="英文简介">
            <el-input v-model="form.reserveTwo" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="英文内容">
            <editor-bar v-model="form.englishContent" :key="form.id" :is-clear="isClear" @change="change" />
          </el-form-item>
          <el-form-item label="阅读数">
            <el-input-number v-model="form.recommend"   style="width: 145px;" />
          </el-form-item>
          <el-form-item label="默认图片地址">
            <el-upload
              v-model="form.defaultPhoto"
              :show-file-list="false"
              :on-success="handleSuccess"
              :on-error="handleError"
              :headers="headers"
              :action="uploadApi"
              class="avatar-uploader"
            >
              <img :src="form.defaultPhoto ? form.defaultPhoto : Avatar" class="avatar">
            </el-upload>
          </el-form-item>
          <el-form-item label="新闻类型">
            <el-select v-model="form.reserveOne" style="width: 145px" placeholder="请选择新闻类型">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>


          <el-form-item label="状态">
            <el-radio v-model="form.reserveOne" :label="0">景区公告</el-radio>
            <el-radio v-model="form.reserveOne" :label="1">新闻</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns.visible('title')" prop="title" label="中文标题" :show-overflow-tooltip="true" align="center" min-width="100" />
        <el-table-column v-if="columns.visible('intro')" prop="intro" label="中文简介" :show-overflow-tooltip="true" align="center" min-width="100" />
        <el-table-column v-if="columns.visible('englishTitle')" prop="englishTitle" label="英文标题" :show-overflow-tooltip="true" align="center" min-width="100" />
        <el-table-column v-if="columns.visible('reserveTwo')" prop="reserveTwo" label="英文简介" :show-overflow-tooltip="true" align="center" min-width="100" />
        <el-table-column v-if="columns.visible('author')" prop="author" label="作者" />
        <el-table-column v-if="columns.visible('createTime')" prop="createTime" label="创建时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('recommend')" label="阅读数" align="center" prop="recommend"></el-table-column>
        <el-table-column v-if="columns.visible('reserveOne')" prop="reserveOne" label="新闻类型" >
          <template slot-scope="scope">{{scope.row.reserveOne | typeFilter}}</template>
        </el-table-column>
        <el-table-column v-if="columns.visible('status')" label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status==1?true:false"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeStatus(scope.row, scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('defaultPhoto')" prop="defaultPhoto" label="默认图片地址" width="120px">
          <template slot-scope="scope"><img style="height: 80px" :src="scope.row.defaultPhoto"></template>
        </el-table-column>
        <el-table-column v-permission="['admin','news:edit','news:del']" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudNews from '@/api/news'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import EditorBar from '@/views/components/wangEditor'

import { getToken } from '@/utils/auth'
import Avatar from '@/assets/images/avatar.png'
import { mapGetters } from 'vuex'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '新闻管理', url: 'api/news', sort: 'id,desc', crudMethod: { ...crudNews }})
const defaultForm = { id: null, title: null, intro: null, content: null, author: null, createTime: null, recommend: null, status: null, defaultPhoto: null, reserveOne: null, reserveTwo: null, englishTitle: null, englishContent: null }
export default {
  name: 'News',
  components: { pagination, crudOperation, rrOperation, udOperation, EditorBar },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {

      Avatar: Avatar,
      headers: {
        'Authorization': getToken()
      },

      isClear: false,
      permission: {
        add: ['admin', 'news:add'],
        edit: ['admin', 'news:edit'],
        del: ['admin', 'news:del']
      },

      typeList: [
        {
          value: 0,
          label: '景区公告'
        }, {
          value: 1,
          label: '景区新闻'
        }
      ],
      imageLogoUrl: '',
      rules: {
      },
      queryTypeOptions: [
        // { key: 'id', display_name: 'ID' },
        { key: 'title', display_name: '标题' },
        // { key: 'recommend', display_name: '推荐' },
        // { key: 'status', display_name: '状态' }
      ]
    }
  },
  mounted() {

  },
  filters: {
    typeFilter(value) {
      if (value === 0) {
        return '景区公告'
      } else if(value===1){
        return '景区新闻'
      }
    }
  },

  computed: {
    ...mapGetters([
      'uploadApi',
      'baseApi'
    ])
  },

  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }
      return true
    },

    change(val) {
      console.log(val)
    },

    // 改变状态
    changeEnabled(data, val) {
      console.log(data)
      // console.log(val);
      if (val == 0) {
        val = 1
      } else {
        val = 0
      }
      data.recommend = val
      this.$confirm('此操作将更改推荐, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudNews.edit(data).then(res => {
          this.crud.notify('更改成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.recommend = !data.recommend
        })
      }).catch(() => {
        data.recommend = !data.recommend
      })
    },
    // 改变状态
    changeStatus(data, val) {
      console.log(data)
      // console.log(val);
      if (val == 0) {
        val = 1
      } else {
        val = 0
      }
      data.status = val
      this.$confirm('此操作将更改推荐, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudNews.edit(data).then(res => {
          this.crud.notify('更改成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.status = !data.status
        })
      }).catch(() => {
        data.status = !data.status
      })
    },
    handleSuccess(response, file, fileList) {
      this.form.defaultPhoto = response
      this.$notify({
        title: '图片修改成功',
        type: 'success',
        duration: 2500
      })
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

<style scoped>
  avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-tooltip__popper{max-width:20%;}
  .el-tooltip__popper,.el-tooltip__popper.is-dark{background:#f5f5f5 !important;
    color: #303133 !important;}
  .text {
    text-align:left;
  }
  /deep/ .w-e-text-container {
    height: 420px !important;
  }
</style>
